package com.hrma.controller;

import com.github.pagehelper.Page;
import com.hrma.entity.*;
import com.hrma.services.AttendanceService;
import com.hrma.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;

@RestController
@RequestMapping("/attendance")
@Slf4j
public class AttendanceController {
    private final AttendanceService attendanceService;

    public AttendanceController(AttendanceService attendanceService) {
        this.attendanceService = attendanceService;
    }

    @PostMapping("/add")
    public Result<AttendanceResult> add(@RequestBody AttendanceResult data) {
        log.debug("收到add请求，请求参数：{}", data);
        attendanceService.add(data);
        return Result.ok(data);
    }

    @DeleteMapping("/delete/{id}")
    public Result<?> delete(@PathVariable int id) {
        log.debug("收到delete请求，请求参数：{}", id);
        attendanceService.delete(id);
        return Result.ok(null);
    }

    @PatchMapping("/update")
    public Result<?> update(@RequestBody AttendanceResult data) {
        log.debug("收到update请求，请求参数：{}", data);
        attendanceService.update(data);
        return Result.ok(null);
    }

    @GetMapping("/select")
    public Result<List<SelectResult>> select() {
        log.debug("收到select请求！");
        return Result.ok(attendanceService.select());

    }

    @PostMapping("/list")
    public Result<ListWithCount<Attendance>> getList(@RequestBody AttendanceDTO data) {
        log.debug("收到list请求，请求参数：{}", data);
        Page<Attendance> res = attendanceService.getList(data);

        return Result.ok(new ListWithCount<>(res.getTotal(), res));
    }

    @PostMapping("/updateRule")
    public Result<AttendanceRule> updateRule(@RequestBody AttendanceRule data) {
        log.debug("收到updateRule请求，请求参数：{}", data);
        attendanceService.updateRule(data);
        return Result.ok(data);
    }

    @GetMapping("/getRule")
    public Result<AttendanceRule> getRule() {
        log.debug("收到getRule请求，请求参数!");
        return Result.ok(attendanceService.getRule());
    }

    @PostMapping("/uploadAttendance")
    public Result<?> uploadAttendance(MultipartHttpServletRequest request) {
        log.debug("收到uploadAttendance请求!");
        request.getMultiFileMap().forEach((name, f) -> {
            try {
                attendanceService.handleUpload(f.get(0));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        return Result.ok(null);
    }

}
